#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unordered_map>

// 1. 定义命令行提示符的大小，命令行提示输出的格式，命令行的大小
#define COMMAND_PROMPT_SIZE 1024
#define FORMAT "[%s@%s %s]# "
#define COMMAND_SIZE 1024
// 2. 
#define MAXARGC 128
char *g_argv[MAXARGC];
int g_argc = 0;

char cwd[1024];
char cwdenv[1024];

int lastcode = 0;
// 2. 环境变量表
#define MAX_ENVS 100
char *g_env[MAX_ENVS];
int g_envs = 0;

// 3.
std::unordered_map<std::string, std::string> alias_list;

const char *GetUserName()
{
	const char *name = getenv("USER");
	return name == NULL ? "None" : name;
}
const char *GetHostName()
{
	const char *hostname = getenv("HOSTNAME");
	return hostname == NULL ? "None" : hostname;
	
	//char *hostname;
	//gethostname(hostname, 256);
	//return hostname;
}

const char *GetPwd()
{
	//const char *pwd = getenv("PWD");
	const char *pwd = getcwd(cwd, sizeof(cwd));
	if (pwd != NULL)
	{
		snprintf(cwdenv, sizeof(cwdenv), "PWD=%s", pwd);
		putenv(cwdenv);
	}
	return pwd = NULL ? "None" : pwd;
}

const char *GetHome()
{
	const char *home = getenv("HOME");
	return home == NULL ? "" : home;
}

void InitEnv()
{
	extern char **environ;
	memset(g_env, 0, sizeof(g_env));
	g_envs = 0;

	for (int i = 0; environ[i]; i++)
	{
		g_env[i] = (char*)malloc(strlen(environ[i])+1);
		strcpy(g_env[i], environ[i]);
		g_envs++;
	}
	g_env[g_envs++] = (char*)"HAHA=for_test";
	g_env[g_envs] = NULL;

	for (int i = 0; g_env[i]; i++)
	{
		putenv(g_env[i]);
	}
}

std::string DirName(const char *pwd)
{
#define SLASH "/"
	std::string dir = pwd;
	if (dir == SLASH) return SLASH;
	auto pos = dir.rfind(SLASH);
	if (pos == std::string::npos) return "BUG?";
	return dir.substr(pos+1);
}

void MakeCommandPrompt(char cmd_prompt[], int size)
{
	snprintf(cmd_prompt, size, FORMAT, GetUserName(), GetHostName(), DirName(GetPwd()).c_str());
}

void PrintCommandPrompt()
{
	char prompt[COMMAND_PROMPT_SIZE];
	MakeCommandPrompt(prompt, sizeof(prompt));
	printf("%s", prompt);
	fflush(stdout);
}

bool GetCommandLine(char *out, int size)
{
	char *c = fgets(out, size, stdin);
	if (c == NULL) return false;
	out[strlen(out)-1] = 0;
	if(strlen(out) == 0) return false;
	return true;
}

bool CommandParse(char *commandLine)
{
#define SEP " "
	g_argc = 0;
	// "ls -a -l" -> "ls" "-a" "-l"
	g_argv[g_argc++] = strtok(commandLine, SEP);
	
	while(g_argv[g_argc++] = strtok(nullptr, SEP));
	// 因为把返回的NULL也放入了g_argv[]中，所以argc多一个
	g_argc--;
	return g_argc > 0 ? true : false;
}

void PrintArgv()
{
	for (int i = 0; g_argv[i]; i++)
	{
		printf("argv[%d]->%s\n", i, g_argv[i]);
	}
	printf("argc: %d\n", g_argc);
}

bool Cd()
{	
	if (g_argc == 1)
	{
		std::string home = GetHome();
		if (home.empty()) return true;
		chdir(home.c_str());
	}
	else
	{
		std::string where = g_argv[1];
		// cd -    cd ~
		if (where == "-")
		{
			chdir(getenv("OLDPWD"));		
		}
		else if (where == "~")
		{
			chdir(GetHome());
		}
		else
		{
			chdir(where.c_str());
		}
	}
	return true;
}

bool Echo()
{
	if (g_argc == 2)
	{
		//echo "hello world"
		//echo $?
		//echo $PATH
		std::string opt = g_argv[1];
		if (opt == "$?")
		{
			std::cout << lastcode << std::endl;
			lastcode = 0;
		}
		else if (opt[0] == '$')
		{
			std::string env_name = opt.substr(1);
			const char *env_value = getenv(env_name.c_str());
			if (env_value)
				std::cout << env_value << std::endl;
		}
		else
		{
			std::cout << opt << std::endl;
		}
	}
	return true;
}

bool CheckAndExecuteBuiltin()
{
	std::string cmd = g_argv[0];
	if (cmd == "cd")
	{
		Cd();
		return true;
	}	
	else if (cmd == "echo")
	{
		Echo();
		return true;
	}
	return false;
}

int Execute()
{
	pid_t id = fork();
	if (id == 0)
	{
		//child
		execvp(g_argv[0], g_argv);
		exit(1);
	}
	int status = 0;
	//father
	pid_t rid = waitpid(id, &status, 0);
	if (rid > 0)
	{
		lastcode = WEXITSTATUS(status);
	}

	return 0;
}

int main()
{
	// shell 启动的时候，从系统中获取环境变量
	// 我们的shell环境变量信息从父进程bash来
	
	InitEnv();

	while(true)
	{
		// 1. 输出命令行提示符
		PrintCommandPrompt();

		// 2. 获取用户输入的命令
		char commandLine[COMMAND_SIZE];
		if (!GetCommandLine(commandLine, sizeof(commandLine)))
			continue;

		//printf("%s\n", commandLine);
		
		// 3. 命令行分析 -- "ls -a -l" -> "ls" "-a" "-l"
		if (!CommandParse(commandLine))
			continue;
		//PrintArgv();

		// 4. 检测并处理内建命令
		if (CheckAndExecuteBuiltin())
			continue;

		// 5. 执行命令 -- 创建子进程，程序替换执行命令
		Execute();
	}	
	return 0;
}
